Completed
Push — master ( c8ba67...05deb1 )
by Alejandro
21s queued 12s
created

SearchField.render   A

Complexity

Conditions 1

Size

Total Lines 23
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 23
ccs 0
cts 4
cp 0
rs 9.376
c 0
b 0
f 0
cc 1
crap 2
1
import React, { useState } from 'react';
2
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
3
import { faSearch as searchIcon } from '@fortawesome/free-solid-svg-icons';
4
import PropTypes from 'prop-types';
5
import classNames from 'classnames';
6
import './SearchField.scss';
7
8 4
const DEFAULT_SEARCH_INTERVAL = 500;
9
let timer;
10
11 4
const propTypes = {
12
  onChange: PropTypes.func.isRequired,
13
  className: PropTypes.string,
14
  placeholder: PropTypes.string,
15
  large: PropTypes.bool,
16
  noBorder: PropTypes.bool,
17
};
18
19 4
const SearchField = ({ onChange, className, placeholder = 'Search...', large = true, noBorder = false }) => {
20
  const [ searchTerm, setSearchTerm ] = useState('');
21
22
  const resetTimer = () => {
23
    clearTimeout(timer);
24
    timer = null;
25
  };
26 1
  const searchTermChanged = (newSearchTerm, timeout = DEFAULT_SEARCH_INTERVAL) => {
27
    setSearchTerm(newSearchTerm);
28
29
    resetTimer();
30
31
    timer = setTimeout(() => {
32
      onChange(newSearchTerm);
33
      resetTimer();
34
    }, timeout);
35
  };
36
37
  return (
38
    <div className={classNames('search-field', className)}>
39
      <input
40
        type="text"
41
        className={classNames('form-control search-field__input', {
42
          'form-control-lg': large,
43
          'search-field__input--no-border': noBorder,
44
        })}
45
        placeholder={placeholder}
46
        value={searchTerm}
47
        onChange={(e) => searchTermChanged(e.target.value)}
48
      />
49
      <FontAwesomeIcon icon={searchIcon} className="search-field__icon" />
50
      <div
51
        className="close search-field__close"
52
        hidden={searchTerm === ''}
53
        id="search-field__close"
54
        onClick={() => searchTermChanged('', 0)}
55
      >
56
        &times;
57
      </div>
58
    </div>
59
  );
60
};
61
62 4
SearchField.propTypes = propTypes;
63
64
export default SearchField;
65